import { defineStore } from 'pinia'
import { ref } from 'vue'
import { request } from '../utils/request'
import { ElMessage } from 'element-plus'

export interface User {
  id: number
  username: string
  email?: string
  nickname?: string
  role: string
}

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('admin_token'))

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const response = await request.post('/auth/login', {
        username,
        password
      })
      
      if (response.success) {
        token.value = response.data.token
        user.value = response.data.user
        localStorage.setItem('admin_token', response.data.token)
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(response.message || '登录失败')
        return false
      }
    } catch (error: any) {
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await request.get('/auth/me')
      if (response.success) {
        user.value = response.data
        return true
      }
      return false
    } catch (error) {
      return false
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('admin_token')
    ElMessage.success('已退出登录')
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    try {
      const response = await request.put('/auth/change-password', {
        oldPassword,
        newPassword
      })
      
      if (response.success) {
        ElMessage.success('密码修改成功')
        return true
      } else {
        ElMessage.error(response.message || '修改失败')
        return false
      }
    } catch (error: any) {
      ElMessage.error(error.message || '修改失败')
      return false
    }
  }

  return {
    user,
    token,
    login,
    getUserInfo,
    logout,
    changePassword
  }
})